//
//  MapMainView.m
//  dataGathering
//
//  Created by apple on 14-11-6.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "MapMainView.h"
#import "MapLayersAndCollectedDataView.h"
#import "GraphicCalloutViewController.h"
#import "SpatialSearchPolygonHelper.h"
#import "AttrDataSearchViewController.h"
#import "NSDate+toFormattedString.h"
#import "GPSRecordingViewController.h"
#import "LatestLayerModelManager.h"
#import "FileUtil.h"
#import "SpatialSearchIndicatorViewController.h"
#import "ReGatheringDataViewController.h"


@interface MapMainView ()
@property(nonatomic, retain)workSet *currentWorkSet;
@property(nonatomic, retain)NSString *currentRecordingType;
@property(nonatomic, retain)NSString *currentRecordingMainTYpe;
@property(nonatomic, strong)newCollectedDataViewViewController *collectedDataVC;


@property(nonatomic, retain)NSTimer *trackingCurrentLocationTimer;

@property(nonatomic, retain)HandDrawingHandler *handDrawingHandler;
@property(nonatomic, retain)SpatialSearchHandler *spatialSearchHandler;
@property(nonatomic, retain)NSMutableDictionary *graphicDict;

@property (nonatomic, strong) GraphicCalloutViewController *calloutVC;

@property(nonatomic, strong)GPSRecordingViewController *gpsRecordingVC;

@property (weak, nonatomic) NSTimer *gpsRecordingTimer;
@property(nonatomic,retain)NSMutableArray *gpsRecordingTimeArray;

@property(nonatomic,retain)NSMutableDictionary *layerModelsArray;
@property(nonatomic,retain)NSMutableDictionary *mapLayerModelsArray;

@property(nonatomic,retain)collectedData *toReGatheringData;

@property(nonatomic, retain)FeatureDataManager *featureDataManager;
@property(nonatomic, retain)NSMutableArray *featureQueryResultList;

@end

@implementation MapMainView
BOOL isReGathering;


-(void)setCurrentType:(NSString *)type
{
    _currentRecordingType = type;
}

-(void)setMainType:(NSString *)mainType
{
    _currentRecordingMainTYpe = mainType;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isReGathering = NO;
    
    NSError *error;
    NSString* clientID = @"hzeDdybqNoj9y2sj";
    [AGSRuntimeEnvironment setClientID:clientID error:&error];
    
    _gpsRecordingTimeArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    _currentWorkSet = [[currentWorkSetManager sharedInstance] getCurrentWorkSet];
    
    _graphicDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    _layerModelsArray = [[NSMutableDictionary alloc] initWithCapacity:10];
    _mapLayerModelsArray = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    CGRect frame = CGRectMake(0, 0, 240, 48);
    _calloutVC = [self.storyboard instantiateViewControllerWithIdentifier:@"calloutView"];
    [_calloutVC.view setFrame:frame];
    //[_calloutVC.view setClipsToBounds:YES];
    

    _trackingCurrentLocationTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleTrackingTimer:) userInfo:nil repeats:YES];
    
    if([_currentWorkSet isTracking]){
        [[NSRunLoop currentRunLoop] addTimer:_trackingCurrentLocationTimer forMode:NSDefaultRunLoopMode];
    }

    
    //Add a basemap tiled layer
    self.mainMapVIew.layerDelegate = self;
    self.mainMapVIew.touchDelegate = self;
    //NSURL* url = [NSURL URLWithString:@"http://services.arcgisonline.com/arcgis/rest/services/ESRI_Imagery_World_2D/MapServer"];
    //AGSTiledMapServiceLayer *tiledLayer = [AGSTiledMapServiceLayer tiledMapServiceLayerWithURL:url];
    //[self.mainMapVIew addMapLayer:tiledLayer withName:@"Basemap Tiled Layer"];
    
    NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/BaseTPK/"] stringByAppendingString:@"矢量"] stringByAppendingString:@".tpk"];
    AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
    [_mainMapVIew addMapLayer:newLayer withName:@"Basemap Tiled Layer"];
    
    
    //NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/TPK/"] stringByAppendingString:@"江苏省-影像切片1"] stringByAppendingString:@".tpk"];
    //AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
    //[newLayer setName:@"test base map"];
    //[_mainMapVIew addMapLayer:newLayer withName:@"test base map"];
    
    
    
    
    

    
    
    self.mainMapVIew.callout.delegate = self;
    
    locationMgr = [[CLLocationManager alloc] init];
    locationMgr.delegate = self;
    locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        [locationMgr requestAlwaysAuthorization];// 前后台同时定位
    }

    [locationMgr startUpdatingLocation];
    [locationMgr startUpdatingHeading];
    
    [self addFeatureLayers];
    AGSGraphicsLayer* myGraphicsLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mainMapVIew addMapLayer:myGraphicsLayer withName:@"GATHERINGDRAWLAYER"];
    [self refreshAllCollectedDataOnMapview];
    
    _mainMenuFormSheet = nil;
    [_titleLabel setText:_collectionTitle];
    
    _mapLayersButton = [[UIButton alloc] initWithFrame:CGRectMake(1024-128-24, 40, 72, 72)];
    [_mapLayersButton setImage:[UIImage imageNamed:@"btn_图层_u852.png"] forState:UIControlStateNormal];
    [_mapLayersButton setImage:[UIImage imageNamed:@"btn_图层_u852_selected.png"] forState:UIControlStateHighlighted];
    [_mapLayersButton setImage:[UIImage imageNamed:@"btn_图层_u852_selected.png"] forState:UIControlStateSelected];
    [_mapLayersButton addTarget:self action:@selector(showMapLayersView) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_mapLayersButton];
    
    _searchButton = [[UIButton alloc] initWithFrame:CGRectMake(1024-56-24, 40, 72, 72)];
    [_searchButton setImage:[UIImage imageNamed:@"u664.png"] forState:UIControlStateNormal];
    [_searchButton setImage:[UIImage imageNamed:@"btn_查询_u850_selected.png"] forState:UIControlStateHighlighted];
    [_searchButton setImage:[UIImage imageNamed:@"btn_查询_u850_selected.png"] forState:UIControlStateSelected];
    [_searchButton addTarget:self action:@selector(showDataSearchView) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_searchButton];
    
    _addTaskButtonView = [[UIButton alloc] initWithFrame:CGRectMake(24-2, 64+68-1, 52, 52)];
    [_addTaskButtonView setImage:[UIImage imageNamed:@"u855.png"] forState:UIControlStateNormal];
    [_addTaskButtonView addTarget:self action:@selector(showNewDataWindow) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_addTaskButtonView];
    
    
    
    
    [self initCurrentGeometryIndicatorView];
    
    AGSSpatialReference *spatialRef = [AGSSpatialReference spatialReferenceWithWKID:4490];
    currentRecordingPolygon = [[AGSMutablePolygon alloc] initWithSpatialReference:spatialRef];
    [currentRecordingPolygon addRingToPolygon];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRecordingLocation:) name:@"startRecordingLocation" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseRecordingLocation:) name:@"pauseRecordingLocation" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopRecordingLocation) name:@"stopRecordingLocation" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishRecordingLocation) name:@"finishRecordingLocation" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addDotLocation) name:@"addDotLocation" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAllCollectedDataOnMapview) name:@"refreshAllCollectedDataOnMapview" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAllCollectedDataOnMapview) name:@"collectedDataRemoved" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMediaPicker:) name:@"presentMediaPicker" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllCallout) name:@"selectedcollectedDataRemoved" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginSpatialSearchMode:) name:@"toSpatialSearchMode" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitSpatialSearchMode:) name:@"exitSpatialSearchMode" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeCallout) name:@"closeCallout" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showSelectedData:) name:@"showSelectedData" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeDataDetail) name:@"dataDetailViewWillPop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMapLayersView) name:@"closeMapLayerView" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showImageShower:) name:@"presentImageShower" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(maplayersVisibleChange:) name:@"maplayersVisibleChange" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reGatheringSelectedData:) name:@"reGatheringSelectedData" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMapLayers:) name:@"offlineFileChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forkToLocal:) name:@"forkToLocal" object:nil];
    
    _handDrawingHandler = [[HandDrawingHandler alloc] initWithMapView:_mainMapVIew];
    _handDrawingHandler.delegate = self;
    
    _spatialSearchHandler = [[SpatialSearchHandler alloc] initWithMapView:_mainMapVIew];
    _spatialSearchHandler.delegate = self;
    
    _featureOnlineLayersDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    _featureOfflineLayersDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    _mapOnlineLayerDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    _mapOfflineLayerDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    _featureDataManager = [FeatureDataManager sharedInstance];
    _featureDataManager.delegate = self;
    
    

#warning test insert image layers
    //[self insertImageLayers];
    
}

-(void)forkToLocal: (NSNotification*)noti
{
    AGSGraphic *graphic = [noti object];
    
    collectedData *newData;
    newData = [[collectedData alloc] initWithAllAttr:@"" :@"" :@"1" :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"realname"] :[[NSDate date] toFormattedString] :[[NSDate date] toFormattedString] :nil :[graphic geometry] :_currentRecordingMainTYpe :_currentRecordingType];
    
    [[[currentWorkSetManager sharedInstance] getCurrentWorkSet] addNewCollectedData:newData];
    [[currentWorkSetManager sharedInstance] addCollectedData:[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] name] :newData];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAllCollectedDataOnMapview" object:nil];
    
    _collectedDataVC = (newCollectedDataViewViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"newCollectedDataViewController"];
    [_collectedDataVC setGeometry:[graphic geometry]];
    [_collectedDataVC setData:newData];
    [_collectedDataVC setType:_currentRecordingType];
    [_collectedDataVC setMainType:_currentRecordingMainTYpe];
    _collectedDataVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
    
    [self.view addSubview:_collectedDataVC.view];

}


-(void)reGatheringSelectedData: (NSNotification*)noti
{
    isReGathering = YES;
    collectedData *toReGatheringData = (collectedData*)[noti object];
    _toReGatheringData = toReGatheringData;
    _currentRecordingMainTYpe = [toReGatheringData mainType];
    _currentRecordingType = [toReGatheringData type];
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    self.mainMapVIew.touchDelegate = self;
    
    //_addTaskButtonView.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
    [UIView animateWithDuration:0.1f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        //_addTaskButtonView.alpha = 1.f;
        //_addTaskButtonView.transform = CGAffineTransformMakeScale(0.1, 0.1);
        CGRect formSheetRect = _addTaskButtonView.frame;
        formSheetRect.size.width = 1;
        formSheetRect.size.height = 1;
        _addTaskButtonView.frame = formSheetRect;
        
        
        
        if([_mapLayersButton isSelected]){
            [_mapLayersButton setSelected:NO];
            
            CGRect formSheetRect = _mapLayersVC.view.frame;
            formSheetRect.origin.x += 488;
            _mapLayersVC.view.frame = formSheetRect;
            
        }
        
        if([_searchButton isSelected]){
            [_searchButton setSelected:NO];
            
            CGRect formSheetRect = _dataSearchNavNC.view.frame;
            formSheetRect.origin.x += 488;
            _dataSearchNavNC.view.frame = formSheetRect;
            
        }
        
    } completion:^(BOOL finished) {
        
        [_mapLayersVC.view removeFromSuperview];
        [_dataSearchNavNC.view removeFromSuperview];
        
        _addTaskButtonView.alpha = 0.f;
        
        if(_addNewDataNavVC == nil || [_addNewDataNavVC.view isHidden]){
            _addNewDataNavVC = [self.storyboard instantiateViewControllerWithIdentifier:@"addNewDataNavWindow"];
            _addNewDataNavVC.view.frame = CGRectMake(4, 118, 328, 448);
            _addNewDataNavVC.view.alpha = 0;
            
            UIButton *exitAddNewDataViewButton = (UIButton*)[[[[_addNewDataNavVC childViewControllers] objectAtIndex:0] topViewController].view viewWithTag:1];
            
            [exitAddNewDataViewButton addTarget:self action:@selector(removeNewDataWindow) forControlEvents:UIControlEventTouchUpInside];
        }
        [self.view addSubview:_addNewDataNavVC.view];
        
        
        [UIView animateWithDuration:0.2 animations:^{
            _addNewDataNavVC.view.alpha = 1;
            
        } completion:^(BOOL finished) {
            
        }];
        
        
    }];

    
}

-(void)exitSpatialSearchMode: (NSNotification*)noti
{
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    _mainMapVIew.touchDelegate = self;
}

-(void)refreshMapLayers :(NSNotification*)noti
{
    [SVProgressHUD showWithStatus:@"图层刷新中,请稍候" maskType:SVProgressHUDMaskTypeBlack];
    NSString *changedLayerName = (NSString*)[noti object];
    NSString *changedLayerNameOnlineName = [changedLayerName stringByAppendingString:@".online"];
    NSString *changedLayerNameOfflineName = [changedLayerName stringByAppendingString:@".offline"];
    if(![_mainMapVIew mapLayerForName:changedLayerNameOfflineName])
    {
        /*no corresponding offline layer of changed name found, should add new offline layer*/
        
        if([[_mainMapVIew mapLayerForName:changedLayerNameOnlineName] isMemberOfClass:[AGSFeatureLayer class]])
        {
            /*changed layer is offline AGSFeatureLayer*/
        } else {
            /*changed layer is offline AGSLocalTileLayer*/
            NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/TPK/"] stringByAppendingString:changedLayerName] stringByAppendingString:@".tpk"];
            AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
            if(![_currentWorkSet isOnlineLayerDisplayed] && [[_mainMapVIew mapLayerForName:changedLayerNameOnlineName] isVisible])
            {
                [[_mainMapVIew mapLayerForName:changedLayerNameOnlineName] setVisible:NO];
                [newLayer setVisible:YES];
            } else {
                [newLayer setVisible:NO];
            }
            [newLayer setName:[changedLayerName stringByAppendingString:@".offline"]];
            NSInteger indexOfOnlineLayer = 0;
            for(AGSLayer *l in [_mainMapVIew mapLayers])
            {
                if([[l name] isEqualToString:changedLayerNameOnlineName])
                {
                    break;
                } else {
                    indexOfOnlineLayer++;
                }
            }
            [_mainMapVIew insertMapLayer:newLayer withName:[changedLayerName stringByAppendingString:@".offline"] atIndex:(indexOfOnlineLayer+1)];
            [_mapOfflineLayerDict setObject:newLayer forKey:[changedLayerName stringByAppendingString:@".offline"]];
        }
    } else {
        /*Found corresponding offline layer to remove*/
        [_mainMapVIew removeMapLayerWithName:changedLayerNameOfflineName];
        
        [_mapOfflineLayerDict removeObjectForKey:changedLayerNameOfflineName];
        [_featureOfflineLayersDict removeObjectForKey:changedLayerNameOfflineName];
        if(![_currentWorkSet isOnlineLayerDisplayed] && [[_mainMapVIew mapLayerForName:changedLayerNameOfflineName] isVisible])
        {
            [[_mainMapVIew mapLayerForName:changedLayerNameOnlineName] setVisible:YES];
        }
        
    }
    [SVProgressHUD dismiss];
    
}

-(void)maplayersVisibleChange :(NSNotification*)noti
{
    for(AGSLayer *l in [_mainMapVIew mapLayers])
    {
        NSLog(@"layer name is %@ and visible is %@",[l name],[l isVisible]?@"yes":@"no");
    }
    AGSLayer *offlayer = [_mainMapVIew mapLayerForName:[(NSString*)[noti object] stringByAppendingString:@".offline"]];
    AGSLayer *onlayer = [_mainMapVIew mapLayerForName:[(NSString*)[noti object] stringByAppendingString:@".online"]];
    
    if((offlayer && [offlayer isVisible]) || (onlayer && [onlayer isVisible]))
    {
        if(offlayer){
            [offlayer setVisible:NO];
        }
        if(onlayer){
            [onlayer setVisible:NO];
        }
    } else {
        if([_currentWorkSet isOnlineLayerDisplayed])
        {
            [[_mainMapVIew mapLayerForName:[(NSString*)[noti object] stringByAppendingString:@".online"]] setVisible:YES];
        } else {
            [[_mainMapVIew mapLayerForName:[(NSString*)[noti object] stringByAppendingString:@".offline"]] setVisible:YES];
        }
    }
    
    for(AGSLayer *l in [_mainMapVIew mapLayers])
    {
        NSLog(@"--------layer name is %@ and visible is %@",[l name],[l isVisible]?@"yes":@"no");
    }
}

-(void)resetOnlineLayersVisible :(BOOL)isOnline
{
    for (AGSLayer *layer in [_mainMapVIew mapLayers])
    {
        if([layer isVisible])
        {
            if([layer isMemberOfClass:[AGSTiledMapServiceLayer class]])
            {
                AGSLayer *foundlayer = [_mapOfflineLayerDict objectForKey:[[layer name] stringByAppendingString:@".offline"]];
                if(foundlayer){
                    [foundlayer setVisible:YES];
                }
            }
            if([layer isMemberOfClass:[AGSGraphic class]])
            {
                AGSLayer *foundlayer = [_featureOfflineLayersDict objectForKey:[[layer name] stringByAppendingString:@".offline"]];
                if(foundlayer){
                    [foundlayer setVisible:YES];
                }
            }
        }
    }
}

-(BOOL)checkIfMapLayersIsVisible: (NSString*)layername
{
    AGSLayer *offlayer = [_mainMapVIew mapLayerForName:[layername stringByAppendingString:@".offline"]];
    AGSLayer *onlayer = [_mainMapVIew mapLayerForName:[layername stringByAppendingString:@".online"]];
    if(offlayer && [offlayer isVisible]){
        return [offlayer isVisible];
    } else if(onlayer && [onlayer isVisible]){
        return [onlayer isVisible];
    } else {
        return NO;
    }
}

-(void)addFeatureLayers
{
    NSError *error;
    
    for(MapGroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] map] groups])
    {
        for(MapLayerModel *lModel in [gModel layers])
        {
            NSString *filePath = [[lModel name] stringByAppendingString:@".tpk"];
            if([FileUtil checkIfFileDownloaded:filePath :FileTypeTPK])
            {
                NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/TPK/"] stringByAppendingString:[lModel name]] stringByAppendingString:@".tpk"];
                AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
                [newLayer setVisible:NO];
                [newLayer setName:[lModel name]];
                [_mainMapVIew addMapLayer:newLayer withName:[[lModel name] stringByAppendingString:@".offline"]];
                [_mapOfflineLayerDict setObject:newLayer forKey:[[lModel name] stringByAppendingString:@".offline"]];
            }
            AGSTiledMapServiceLayer *newLayer = [[AGSTiledMapServiceLayer alloc] initWithURL:[NSURL URLWithString:[lModel url]]];
            [newLayer setVisible:NO];
            [newLayer setName:[lModel name]];
            [_mainMapVIew addMapLayer:newLayer withName:[[lModel name] stringByAppendingString:@".online"]];
            [_mapOnlineLayerDict setObject:newLayer forKey:[[lModel name] stringByAppendingString:@".online"]];
            
            //AGSFeatureLayer *newFeatureLayer = [[AGSFeatureLayer alloc] initWithURL:[[NSURL alloc] initWithString:[lModel url]] mode:AGSFeatureLayerModeOnDemand error:&error];
            //NSLog(@"initiate new feature layer error is %@",error);
            //[_mapLayerModelsArray setValue:newFeatureLayer forKey:[lModel name]];
            
            //[newFeatureLayer setVisible:YES];
            
            //[_mainMapVIew addMapLayer:newFeatureLayer withName:[lModel name]];
            //[_tpkLayersDict setObject:newFeatureLayer forKey:[lModel name]];
        }
    }
    for(GroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] feature] groups])
    {
        for(LayerModel *lModel in [gModel layers])
        {
            NSString *filePath = [[lModel name] stringByAppendingString:@".sqlite"];
            if([FileUtil checkIfFileDownloaded:filePath :FileTypeFeatureData])
            {
                AGSGraphicsLayer *newGraphicLayer = [[AGSGraphicsLayer alloc] initWithSpatialReference:_mainMapVIew.spatialReference];
                //[self loadGraphicLayer];
                [newGraphicLayer setVisible:NO];
                [newGraphicLayer setName:[lModel name]];
                [_mainMapVIew addMapLayer:newGraphicLayer withName:[[lModel name] stringByAppendingString:@".offline"]];
                [_featureOfflineLayersDict setObject:newGraphicLayer forKey:[[lModel name] stringByAppendingString:@".offline"]];
            }
            AGSFeatureLayer *newFeatureLayer = [[AGSFeatureLayer alloc] initWithURL:[[NSURL alloc] initWithString:[lModel url]] mode:AGSFeatureLayerModeOnDemand error:&error];
            NSLog(@"initiate new feature layer error is %@",error);
            newFeatureLayer.queryDelegate = self;
            if(newFeatureLayer != nil){
                
                NSLog(@"render is %@",[[newFeatureLayer renderer] encodeToJSON]);
                
                
                [_layerModelsArray setValue:newFeatureLayer forKey:[lModel name]];
                
                [newFeatureLayer setVisible:NO];
                [newFeatureLayer setName:[lModel name]];
                
                newFeatureLayer.calloutDelegate = self;
                
                [_mainMapVIew addMapLayer:newFeatureLayer withName:[[lModel name] stringByAppendingString:@".online"]];
                [_featureOnlineLayersDict setObject:newFeatureLayer forKey:[[lModel name] stringByAppendingString:@".online"]];
            }
            
            
        }
    }
}

- (void)setSelectedLayerVisibleUsingName :(NSString*)layername visible:(BOOL)isVisible
{
    if([_layerModelsArray objectForKey:layername] != nil)
    {
        [(AGSFeatureLayer*)[_layerModelsArray objectForKey:layername] setVisible:isVisible];
    }
    if([_mapLayerModelsArray objectForKey:layername] != nil)
    {
        
    }
}

-(void)insertImageLayers
{
    NSInteger arrayNumber = [[self.mainMapVIew mapLayers] count];
    NSURL* url = [NSURL URLWithString:@"http://services.arcgisonline.com/arcgis/rest/services/ESRI_StreetMap_World_2D/MapServer"];
    AGSTiledMapServiceLayer *tiledLayer = [AGSTiledMapServiceLayer tiledMapServiceLayerWithURL:url];
    //[_mainMapVIew insertMapLayer:tiledLayer withName:@"testImageLayer" atIndex:(arrayNumber-1)];
    [_mainMapVIew addMapLayer:tiledLayer];
    
}

-(void)closeDataDetail
{
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] clearSelection];
}

-(void)showSelectedData:(NSNotification*)noti
{
    collectedData *data = (collectedData*)[noti object];
    AGSGraphic *selectedG = [_graphicDict objectForKey:[data idNumber]];
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] setSelected:YES forGraphic:selectedG];
    [self.mainMapVIew zoomToGeometry:[selectedG geometry] withPadding:200 animated:YES];
    
}

-(void)closeCallout
{
    if([_mapLayersButton isSelected]){
        [self showMapLayersView];
    }
}

-(void)beginSpatialSearchMode :(NSNotification*)noti
{
    NSIndexPath* path = (NSIndexPath*)[noti object];
    [_spatialSearchHandler setMode:[path row]];
}

-(void)removeAllCallout
{
    [self.mainMapVIew.callout dismiss];
    
}

-(void)calloutDidDismiss:(AGSCallout*)callout
{
    AGSGraphicsLayer* layer  = (AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"];
    [layer clearSelection];
}

- (BOOL) callout:(AGSCallout *)callout willShowForFeature:(id<AGSFeature>)feature layer:(AGSLayer<AGSHitTestable> *)layer mapPoint:(AGSPoint *)mapPoint
{
    if([[layer name] compare:@"GATHERINGDRAWLAYER"] != NSOrderedSame && ![layer isMemberOfClass:[AGSFeatureLayer class]])
    {
        return NO;
    }
    AGSGraphic* graphic = (AGSGraphic*)feature;
    NSLog(@"feature all atribute is %@",[feature allAttributes]);
    
    NSLog(@"graphic all atribute is %@",[graphic allAttributes]);
    
    NSString *type = (NSString*)[graphic attributeForKey:@"type"];
    NSString *name = (NSString*)[graphic attributeForKey:@"name"];
    NSString *idNumber = (NSString*)[graphic attributeForKey:@"idNumber"];
    
    
    [_calloutVC setMapview:self.mainMapVIew];
    [_calloutVC setGraphic:graphic];
    if([layer isMemberOfClass:[AGSFeatureLayer class]])
    {
        [_calloutVC.typeLabel setText:(NSString*)[graphic attributeForKey:@"NAME"]];
        [_calloutVC.idLabel setText:@""];
        [_calloutVC setIsFeatureDataCallout:YES];
    } else {
        [_calloutVC.typeLabel setText:type];
        [_calloutVC.idLabel setText:idNumber];
        [_calloutVC setIsFeatureDataCallout:NO];
    }
    self.mainMapVIew.callout.customView = _calloutVC.view;
    [self.mainMapVIew.callout setTitle:(NSString*)[graphic attributeForKey:@"NAME"]];
    
    [(AGSGraphicsLayer*)layer clearSelection];
    //AGSGraphic *selectedG = [_graphicDict objectForKey:[d name]];
    [(AGSGraphicsLayer*)layer setSelected:YES forGraphic:graphic];
    
    if(![layer isMemberOfClass:[AGSFeatureLayer class]])
    {
        [self showSelectedDataDetailView:name];
    }
    
    
    return YES;
}

-(void)showMediaPicker :(NSNotification*)noti
{
    UzysAssetsPickerController* picker = (UzysAssetsPickerController*)[noti object];
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)showImageShower :(NSNotification*)noti
{

    //[self presentViewController:picker animated:YES completion:nil];
}

- (void)handleTrackingTimer: (NSTimer*)timer
{
    [self.mainMapVIew zoomToScale:[self.mainMapVIew mapScale] withCenterPoint:self.mainMapVIew.locationDisplay.location.point animated:YES];
}

- (void)refreshAllCollectedDataOnMapview
{
    while([currentRecordingPolygon numPoints] > 0){
        [currentRecordingPolygon removePointOnRing:0 atIndex:0];
    }
    AGSSimpleFillSymbol *innerSymbol = [AGSSimpleFillSymbol simpleFillSymbol];
    innerSymbol.color = [[UIColor blueColor] colorWithAlphaComponent:0.40];
    innerSymbol.outline.color = [UIColor darkGrayColor];
    
    
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"HANDDRAWINGLAYER"] removeAllGraphics];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeAllGraphics];
    [_graphicDict removeAllObjects];

    _currentWorkSet = [[currentWorkSetManager sharedInstance] getCurrentWorkSet];
    for(collectedData *d in [_currentWorkSet collectedDataList])
    {
        NSMutableDictionary *graphicAttributes;
        graphicAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                             [d type], @"type",
                             [d mainType], @"maintype",
                             [d name], @"name",
                             [d idNumber],@"idNumber",
                             nil];
        
        //NSLog(@"find num is %ld", (long)[(AGSPolygon*)[d geometry] numPoints]);
        AGSGraphic *graphic = [[AGSGraphic alloc] initWithGeometry:[d geometry] symbol:innerSymbol attributes:graphicAttributes];
        
        [_graphicDict setObject:graphic forKey:[d idNumber]];
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:graphic];
    }
}

- (void)startRecordingLocation:(NSNotification*)noti
{
    
    if([_gpsRecordingTimer isValid] && [currentRecordingPolygon numPoints] > 0){
        [_gpsRecordingTimer setFireDate:[NSDate date]];
        return;
    }
    
    float gpsRecordingFrequence = [(NSNumber*)[noti object] floatValue];
    if(_gpsRecordingVC == nil || [_gpsRecordingVC.view isHidden]){
        _gpsRecordingVC = [self.storyboard instantiateViewControllerWithIdentifier:@"gpsRecordingViewController"];
        _gpsRecordingVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
        
        UIButton *exitAddNewDataViewButton = (UIButton*)[[(UIViewController*)[[_gpsRecordingVC childViewControllers] objectAtIndex:0] view] viewWithTag:1];
        
        [exitAddNewDataViewButton addTarget:self action:@selector(cancelRecordingLocation) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:_gpsRecordingVC.view];

    //[[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"isRecordingGeometry"];
    
    _gpsRecordingTimer = [NSTimer scheduledTimerWithTimeInterval:(60.0/gpsRecordingFrequence) target:self selector:@selector(startRecordingGPSLocationTimer) userInfo:nil repeats:YES];
    //locationMgr.delegate = self;
}

-(void)startRecordingGPSLocationTimer
{
    [_xCoordinate setText:[[NSString alloc] initWithFormat:@"%.2f", [self.mainMapVIew.locationDisplay.location.point x]]];
    [_yCoordinate setText:[[NSString alloc] initWithFormat:@"%.2f", [self.mainMapVIew.locationDisplay.location.point y]]];
    
    NSDateFormatter *nsdf2=[[NSDateFormatter alloc] init];
    [nsdf2 setDateStyle:NSDateFormatterMediumStyle];
    [nsdf2 setDateFormat:@"HH:mm:ss"];
    NSString *date=[nsdf2 stringFromDate:[NSDate date]];
    
    AGSSimpleFillSymbol *innerSymbol = [AGSSimpleFillSymbol simpleFillSymbol];
    innerSymbol.color = [[UIColor blueColor] colorWithAlphaComponent:0.40];
    innerSymbol.outline.color = [UIColor darkGrayColor];
    
    AGSPoint *point = [self.mainMapVIew.locationDisplay.location.point mutableCopy];
    
    if([[_gpsCollectingType uppercaseString] isEqualToString:@"POINT"]){
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeGraphic:g];
        g = [[AGSGraphic alloc] initWithGeometry:currentRecordingPolygon symbol:innerSymbol attributes:nil];
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:g];
        
        if(_gpsRecordingVC){
            _gpsRecordingVC.recordingType = @"POINT";
            _gpsRecordingVC.geometry = point;
            _gpsRecordingVC.timeArray = [[NSMutableArray alloc] initWithObjects:date, nil];
            [_gpsRecordingVC reloadTableView];
        }
    } else if ([[_gpsCollectingType uppercaseString] isEqualToString:@"POLYLINE"])
    {
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeGraphic:g];
        g = [[AGSGraphic alloc] initWithGeometry:currentRecordingPolygon symbol:innerSymbol attributes:nil];
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:g];
        [_gpsRecordingTimeArray addObject:date];
        if(_gpsRecordingVC){
            _gpsRecordingVC.recordingType = @"POLYLINE";
            _gpsRecordingVC.geometry = point;
            _gpsRecordingVC.timeArray = _gpsRecordingTimeArray;
            [_gpsRecordingVC reloadTableView];
        }
    } else
    {
        NSLog(@"numerb of points is %d", [currentRecordingPolygon numPoints]);
        [currentRecordingPolygon addPointToRing:point];
        
        
        
        [_gpsRecordingTimeArray addObject:date];
        
        
        
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeGraphic:g];
        g = [[AGSGraphic alloc] initWithGeometry:currentRecordingPolygon symbol:innerSymbol attributes:nil];
        [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:g];
        
        if(_gpsRecordingVC){
            _gpsRecordingVC.recordingType = @"POLYGON";
            _gpsRecordingVC.geometry = currentRecordingPolygon;
            _gpsRecordingVC.timeArray = _gpsRecordingTimeArray;
            [_gpsRecordingVC reloadTableView];
        }
    }

}

-(void)pauseRecordingLocation:(NSNotification*)noti
{
    if (![_gpsRecordingTimer isValid]) {
        return ;
    }
    
    [_gpsRecordingTimer setFireDate:[NSDate distantFuture]];
}

-(void)cancelRecordingLocation
{
    NSLog(@"gps location view dismissed");
    [_gpsRecordingTimer invalidate];
    
    [_gpsRecordingVC.view removeFromSuperview];
    _gpsRecordingVC = nil;
    
    NSLog(@"current geometry point NO is %d",[((AGSPolygon*)currentRecordingPolygon) numPoints]);
    
    NSLog(@"current geometry ring NO is %d",[((AGSPolygon*)currentRecordingPolygon) numRings]);
    while([currentRecordingPolygon numPoints] > 0){
        [currentRecordingPolygon removePointOnRing:0 atIndex:0];
    }
    NSLog(@"after clean point NO is %d",[((AGSPolygon*)currentRecordingPolygon) numPoints]);
    [_gpsRecordingTimeArray removeAllObjects];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelRecordingLocation" object:nil];

}

-(void)addDotLocation
{
    AGSPoint *point = [self.mainMapVIew.locationDisplay.location.point mutableCopy];
    
    NSLog(@"numerb of points is %d", [currentRecordingPolygon numPoints]);
    [currentRecordingPolygon addPointToRing:point];
    
    NSDateFormatter *nsdf2=[[NSDateFormatter alloc] init];
    [nsdf2 setDateStyle:NSDateFormatterMediumStyle];
    [nsdf2 setDateFormat:@"HH:mm:ss"];
    NSString *date=[nsdf2 stringFromDate:[NSDate date]];
    
    [_gpsRecordingTimeArray addObject:date];
    
    AGSSimpleFillSymbol *innerSymbol = [AGSSimpleFillSymbol simpleFillSymbol];
    innerSymbol.color = [[UIColor blueColor] colorWithAlphaComponent:0.40];
    innerSymbol.outline.color = [UIColor darkGrayColor];
    
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeGraphic:g];
    g = [[AGSGraphic alloc] initWithGeometry:currentRecordingPolygon symbol:innerSymbol attributes:nil];
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:g];
    
    if(_gpsRecordingVC){
        _gpsRecordingVC.recordingType = @"POLYGON";
        _gpsRecordingVC.geometry = currentRecordingPolygon;
        _gpsRecordingVC.timeArray = _gpsRecordingTimeArray;
        [_gpsRecordingVC reloadTableView];
    }

}

-(void)finishRecordingLocation
{
    [_gpsRecordingTimeArray removeAllObjects];
    if([_gpsRecordingTimer isValid]){
        [_gpsRecordingTimer invalidate];
    }
    [_gpsRecordingVC.view removeFromSuperview];
    _gpsRecordingVC = nil;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelRecordingLocation" object:nil];
    
    [self removeNewDataWindow];
    
    if([currentRecordingPolygon numPoints] > 0){
        
        [currentRecordingPolygon closePolygon];
        
        collectedData *newData = [[collectedData alloc] initWithAllAttr:@"" :@"" :@"1" :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"realname"] :[[NSDate date] toFormattedString] :[[NSDate date] toFormattedString] :nil :[currentRecordingPolygon copy] :_currentRecordingMainTYpe :_currentRecordingType];
        
        NSLog(@"to add a %ld point g", (long)[(AGSPolygon*)([newData geometry]) numPoints]);
        
        [[[currentWorkSetManager sharedInstance] getCurrentWorkSet] addNewCollectedData:newData];
        [[currentWorkSetManager sharedInstance] addCollectedData:[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] name] :newData];
        
        [self refreshAllCollectedDataOnMapview];
        
        _collectedDataVC = (newCollectedDataViewViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"newCollectedDataViewController"];
        [_collectedDataVC setGeometry:[currentRecordingPolygon copy]];
        [_collectedDataVC setData:newData];
        [_collectedDataVC setType:_currentRecordingType];
        [_collectedDataVC setMainType:_currentRecordingMainTYpe];
        _collectedDataVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
        
        [self.view addSubview:_collectedDataVC.view];
    }
    
}

- (void)stopRecordingLocation
{
    [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"isRecordingGeometry"];
    //locationMgr.delegate = nil;
    if([currentRecordingPolygon numPoints] > 0){
        [currentRecordingPolygon closePolygon];
        
        _collectedDataVC = (newCollectedDataViewViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"newCollectedDataViewController"];
        [_collectedDataVC setGeometry:currentRecordingPolygon];
        [_collectedDataVC setType:_currentRecordingType];
        [_collectedDataVC setMainType:_currentRecordingMainTYpe];
        _collectedDataVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
        
        [self.view addSubview:_collectedDataVC.view];
    }

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
   // NSLog(@"location updated");
    
    //NSLog(@"isrecording? %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"isRecordingGeometry"]);
    
    if([(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"isRecordingGeometry"] isEqualToString:@"NO"] || ![[NSUserDefaults standardUserDefaults] objectForKey:@"isRecordingGeometry"]){
        return;
    }
    
    [_xCoordinate setText:[[NSString alloc] initWithFormat:@"%.2f", [self.mainMapVIew.locationDisplay.location.point x]]];
    [_yCoordinate setText:[[NSString alloc] initWithFormat:@"%.2f", [self.mainMapVIew.locationDisplay.location.point y]]];

    AGSPoint *point = [self.mainMapVIew.locationDisplay.location.point mutableCopy];
    
    NSLog(@"numerb of points is %d", [currentRecordingPolygon numPoints]);
    [currentRecordingPolygon addPointToRing:point];
    
    AGSSimpleFillSymbol *innerSymbol = [AGSSimpleFillSymbol simpleFillSymbol];
    innerSymbol.color = [[UIColor blueColor] colorWithAlphaComponent:0.40];
    innerSymbol.outline.color = [UIColor darkGrayColor];
    
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] removeGraphic:g];
    g = [[AGSGraphic alloc] initWithGeometry:currentRecordingPolygon symbol:innerSymbol attributes:nil];
    [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] addGraphic:g];
    
    if(_gpsRecordingVC){
        _gpsRecordingVC.recordingType = @"POLYGON";
        _gpsRecordingVC.geometry = currentRecordingPolygon;
        [_gpsRecordingVC reloadTableView];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];  
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initCurrentGeometryIndicatorView
{
    [_moveToCurrentLocationButton setImage:[UIImage imageNamed:@"u1063_mouseOver.png"] forState:UIControlStateHighlighted];
}

- (void)exitButtonClicked
{
    
    [_mainMenuFormSheet dismissAnimated:YES completionHandler:^(UIViewController *presentedFSViewController){
        _mainMenuFormSheet = nil;
        [[MZFormSheetBackgroundWindow appearance] setBackgroundColor:[UIColor clearColor]];
        [[MZFormSheetBackgroundWindow appearance] setBackgroundBlurEffect:NO];
        
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
     ];
}

-(void)trackingSwitchChanged:(id)sender
{
    [_currentWorkSet setIsTracking:[((UISwitch*)sender) isOn]];
    [[currentWorkSetManager sharedInstance] updateIsTracking:[_currentWorkSet name] :[((UISwitch*)sender) isOn]];
    
    if(_trackingCurrentLocationTimer && [((UISwitch*)sender) isOn]){
        _trackingCurrentLocationTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleTrackingTimer:) userInfo:nil repeats:YES];
        
        if([_currentWorkSet isTracking]){
            [[NSRunLoop currentRunLoop] addTimer:_trackingCurrentLocationTimer forMode:NSDefaultRunLoopMode];
        }
    } else{

        [_trackingCurrentLocationTimer invalidate];
    }
}

-(void)autoSyncSwitchChanged:(id)sender
{
    [_currentWorkSet setIsAutoSync:[((UISwitch*)sender) isOn]];
    [[currentWorkSetManager sharedInstance] updateIsAutoSync:[_currentWorkSet name] :[((UISwitch*)sender) isOn]];
}

-(void)onlineLayerDisplaySwitchChanged:(id)sender
{
    [_currentWorkSet setIsOnlineLayerDisplayed:[((UISwitch*)sender) isOn]];
    [[currentWorkSetManager sharedInstance] updateIsOnlineLayerDisplayed:[_currentWorkSet name] :[((UISwitch*)sender) isOn]];
    [self resetOnlineLayersVisible:[((UISwitch*)sender) isOn]];
}

-(void)basemaptypeSegmentControlChanged:(id)sender
{
    if([(UISegmentedControl*)sender selectedSegmentIndex] == 0)
    {
        NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/BaseTPK/"] stringByAppendingString:@"矢量"] stringByAppendingString:@".tpk"];
        AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
        [self.mainMapVIew removeMapLayerWithName:@"Basemap Tiled Layer"];
        [_mainMapVIew insertMapLayer:newLayer withName:@"Basemap Tiled Layer" atIndex:0];
        
        
    } else {
        NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [[[appDocumentPath stringByAppendingString:@"/BaseTPK/"] stringByAppendingString:@"影像"] stringByAppendingString:@".tpk"];
        AGSLocalTiledLayer *newLayer = [[AGSLocalTiledLayer alloc] initWithPath:filePath];
        [self.mainMapVIew removeMapLayerWithName:@"Basemap Tiled Layer"];
        [_mainMapVIew insertMapLayer:newLayer withName:@"Basemap Tiled Layer" atIndex:0];
    }
}

- (IBAction)menuButtonClicked:(id)sender {
    
    
    if(_mainMenuFormSheet == nil){
        UIViewController *mainMenuVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mapViewSetting"];
        
        mainMenuVC.view.frame = CGRectMake(0.0, 0.0, 200, 660);
        
        UIButton *exitButton = (UIButton*)[mainMenuVC.view viewWithTag:8];
        [exitButton addTarget:self action:@selector(exitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *usernameLabel = (UILabel*)[mainMenuVC.view viewWithTag:2];
        [usernameLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]];
        
        UILabel *departmentLabel = (UILabel*)[mainMenuVC.view viewWithTag:3];
        [departmentLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"department"]];
        
        UISwitch *trackingSwitch = (UISwitch*)[mainMenuVC.view viewWithTag:4];
        [trackingSwitch setOn:[_currentWorkSet isTracking]];
        [trackingSwitch addTarget:self action:@selector(trackingSwitchChanged:) forControlEvents:UIControlEventValueChanged];
        
        UISwitch *autoSyncSwitch = (UISwitch*)[mainMenuVC.view viewWithTag:5];
        [autoSyncSwitch setOn:[_currentWorkSet isAutoSync]];
        [autoSyncSwitch addTarget:self action:@selector(autoSyncSwitchChanged:) forControlEvents:UIControlEventValueChanged];
        
        UISwitch *onlineLayerDisplaySwitch = (UISwitch*)[mainMenuVC.view viewWithTag:6];
        [onlineLayerDisplaySwitch setOn:[_currentWorkSet isOnlineLayerDisplayed]];
        [onlineLayerDisplaySwitch addTarget:self action:@selector(onlineLayerDisplaySwitchChanged:) forControlEvents:UIControlEventValueChanged];
        
        UISegmentedControl *basemaptypeSegmentControl = (UISegmentedControl*)[mainMenuVC.view viewWithTag:10];
        [basemaptypeSegmentControl setSelectedSegmentIndex:0];
        [basemaptypeSegmentControl addTarget:self action:@selector(basemaptypeSegmentControlChanged:) forControlEvents:UIControlEventValueChanged];
        
        _mainMenuFormSheet = [[MZFormSheetController alloc] initWithViewController:mainMenuVC];
        
        [[MZFormSheetBackgroundWindow appearance] setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]];
        [[MZFormSheetBackgroundWindow appearance] setBackgroundBlurEffect:YES];
        [[MZFormSheetBackgroundWindow appearance] setBlurRadius:5.0];
        _mainMenuFormSheet.shouldDismissOnBackgroundViewTap = YES;
        _mainMenuFormSheet.transitionStyle = MZFormSheetTransitionStyleSlideFromLeft;
        _mainMenuFormSheet.cornerRadius = 0.0;
        _mainMenuFormSheet.landscapeTopInset = 89;
        _mainMenuFormSheet.shadowOpacity = 0.5;
        _mainMenuFormSheet.presentedFormSheetSize = CGSizeMake(200, 660);
        _mainMenuFormSheet.formSheetWindow.transparentTouchEnabled = YES;
        _mainMenuFormSheet.leftInset = 0.0;
        
        [_mainMenuFormSheet presentAnimated:YES completionHandler:^(UIViewController *presentedFSViewController){
            
            
        }
         
         ];
    } else {
        NSLog(@"11");
        [_mainMenuFormSheet dismissAnimated:YES completionHandler:^(UIViewController *presentedFSViewController){
            _mainMenuFormSheet = nil;
            [[MZFormSheetBackgroundWindow appearance] setBackgroundColor:[UIColor clearColor]];
            [[MZFormSheetBackgroundWindow appearance] setBackgroundBlurEffect:NO];
        }
         
         ];
    }
}



#pragma Add New Data Window
- (void)showNewDataWindow
{
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    self.mainMapVIew.touchDelegate = self;
    
    //_addTaskButtonView.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
    [UIView animateWithDuration:0.1f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        //_addTaskButtonView.alpha = 1.f;
        //_addTaskButtonView.transform = CGAffineTransformMakeScale(0.1, 0.1);
        CGRect formSheetRect = _addTaskButtonView.frame;
        formSheetRect.size.width = 1;
        formSheetRect.size.height = 1;
        _addTaskButtonView.frame = formSheetRect;
        
        
        
        if([_mapLayersButton isSelected]){
            [_mapLayersButton setSelected:NO];

                CGRect formSheetRect = _mapLayersVC.view.frame;
                formSheetRect.origin.x += 488;
                _mapLayersVC.view.frame = formSheetRect;

        }
        
        if([_searchButton isSelected]){
            [_searchButton setSelected:NO];
            
            CGRect formSheetRect = _dataSearchNavNC.view.frame;
            formSheetRect.origin.x += 488;
            _dataSearchNavNC.view.frame = formSheetRect;
            
        }
        
    } completion:^(BOOL finished) {
        
        [_mapLayersVC.view removeFromSuperview];
        [_dataSearchNavNC.view removeFromSuperview];
        
        _addTaskButtonView.alpha = 0.f;
        
        if(_addNewDataNavVC == nil || [_addNewDataNavVC.view isHidden]){
            _addNewDataNavVC = [self.storyboard instantiateViewControllerWithIdentifier:@"addNewDataNavWindow"];
            _addNewDataNavVC.view.frame = CGRectMake(4, 118, 328, 448);
            _addNewDataNavVC.view.alpha = 0;
            
            UIButton *exitAddNewDataViewButton = (UIButton*)[[[[_addNewDataNavVC childViewControllers] objectAtIndex:0] topViewController].view viewWithTag:1];

            [exitAddNewDataViewButton addTarget:self action:@selector(removeNewDataWindow) forControlEvents:UIControlEventTouchUpInside];
        }
        [self.view addSubview:_addNewDataNavVC.view];
        
        
        [UIView animateWithDuration:0.2 animations:^{
            _addNewDataNavVC.view.alpha = 1;
            
        } completion:^(BOOL finished) {
            
        }];
        
        
    }];
}

-(void)showDataSearchView
{
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    self.mainMapVIew.touchDelegate = self;
    if([_searchButton isSelected]){
        [_searchButton setSelected:NO];
        [UIView animateWithDuration:0.2 animations:^{
            CGRect formSheetRect = _dataSearchNavNC.view.frame;
            formSheetRect.origin.x += 488;
            _dataSearchNavNC.view.frame = formSheetRect;
            
        } completion:^(BOOL finished) {
            [_dataSearchNavNC.view removeFromSuperview];
        }];
        return;
    }
    
    //if([_mapLayersButton isSelected]){
    
    if(_addTaskButtonView.alpha == 0){
        [self removeNewDataWindow];
    }
        [_mapLayersButton setSelected:NO];
        [UIView animateWithDuration:0.1 animations:^{
            CGRect formSheetRect = _mapLayersVC.view.frame;
            formSheetRect.origin.x += 488;
            _mapLayersVC.view.alpha = 0;
            
        } completion:^(BOOL finished) {
            [_mapLayersVC.view removeFromSuperview];
            
            [_searchButton setSelected:YES];
            
           // if(_dataSearchNavNC == nil || [_dataSearchNavNC.view isHidden]){
                _dataSearchNavNC = [self.storyboard instantiateViewControllerWithIdentifier:@"dataSearchVC"];
                _dataSearchNavNC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
                _dataSearchNavNC.view.alpha = 0;
                
            //}
            [self.view addSubview:_dataSearchNavNC.view];
            
            [UIView animateWithDuration:0.1 animations:^{
                CGRect formSheetRect = _dataSearchNavNC.view.frame;
                formSheetRect.origin.x -= 488;
                _dataSearchNavNC.view.alpha = 1;
                
            } completion:^(BOOL finished) {
                
            }];

        }];


}

-(void)removeNewDataWindow
{
    isReGathering = NO;
    [UIView animateWithDuration:0.2 animations:^{
        _addNewDataNavVC.view.alpha = 0;
    } completion:^(BOOL finished) {
        [_addNewDataNavVC.view removeFromSuperview];
        
        _addTaskButtonView.alpha = 1;
        [UIView animateWithDuration:0.1 animations:^{
            CGRect formSheetRect = _addTaskButtonView.frame;
            formSheetRect.size.width = 52;
            formSheetRect.size.height = 52;
            _addTaskButtonView.frame = formSheetRect;
        } completion:^(BOOL finished) {
            
        }];
    }];
}

- (IBAction)moveToCurrentLocationButtonClicked:(id)sender {

   [self.mainMapVIew zoomToScale:0.5 withCenterPoint:self.mainMapVIew.locationDisplay.location.point animated:YES];
}

-(void) mapViewDidLoad:(AGSMapView*)mapView {
    [self.mainMapVIew.locationDisplay startDataSource];
    
    NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"FeatureData"];
    NSError *error;
    if(![[NSFileManager defaultManager] createDirectoryAtPath:dbpath withIntermediateDirectories:YES attributes:nil error:&error])
    {
        NSLog(@"create directory featureData error is %@",error);
    }
}

-(void)showMapLayersView
{
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    self.mainMapVIew.touchDelegate = self;
    if([_mapLayersButton isSelected]){
        [_mapLayersButton setSelected:NO];
        
        [self.mainMapVIew.callout dismiss];
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect formSheetRect = _mapLayersVC.view.frame;
            formSheetRect.origin.x += 488;
            _mapLayersVC.view.frame = formSheetRect;
            
        } completion:^(BOOL finished) {
            [_mapLayersVC.view removeFromSuperview];
        }];
        return;
    }
    
    if(_addTaskButtonView.alpha == 0){
        [self removeNewDataWindow];
    }
    
        [_searchButton setSelected:NO];
        [UIView animateWithDuration:0.1 animations:^{
            CGRect formSheetRect = _dataSearchNavNC.view.frame;
            formSheetRect.origin.x += 488;
            _dataSearchNavNC.view.alpha = 0;
            
        } completion:^(BOOL finished) {
            [_dataSearchNavNC.view removeFromSuperview];
            
            [_mapLayersButton setSelected:YES];
            
                _mapLayersVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mapLayersVC"];
                _mapLayersVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
                _mapLayersVC.view.alpha = 0;
            [self addChildViewController:_mapLayersVC];
            
            [self.view addSubview:_mapLayersVC.view];
            
            [UIView animateWithDuration:0.1 animations:^{
                CGRect formSheetRect = _mapLayersVC.view.frame;
                formSheetRect.origin.x -= 488;
                _mapLayersVC.view.alpha = 1;
                
            } completion:^(BOOL finished) {
                
            }];
            
        }];
}


-(void)showSelectedDataDetailView :(NSString*)name
{
    [_spatialSearchHandler stop];
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    self.mainMapVIew.touchDelegate = self;
    collectedData *selectedData;
    for(collectedData *d in [_currentWorkSet collectedDataList])
    {
        if([[d name] compare:name] == NSOrderedSame){
            selectedData = d;
        }
    }
    
    if([_mapLayersButton isSelected]){
        [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) collectedDataButtonClicked:nil];
        [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) callSelectedDataDetailView:selectedData];
        
        
        
        [_mapLayersButton setSelected:NO];
        [UIView animateWithDuration:0.2 animations:^{
            CGRect formSheetRect = _mapLayersVC.view.frame;
            formSheetRect.origin.x += 488;
            _mapLayersVC.view.frame = formSheetRect;
            
        } completion:^(BOOL finished) {
            [_mapLayersVC.view removeFromSuperview];
            
            [UIView animateWithDuration:0.1 animations:^{
                CGRect formSheetRect = _dataSearchNavNC.view.frame;
                formSheetRect.origin.x += 488;
                _dataSearchNavNC.view.alpha = 0;
                
            } completion:^(BOOL finished) {
                [_dataSearchNavNC.view removeFromSuperview];
                
                [_mapLayersButton setSelected:YES];
                
                _mapLayersVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mapLayersVC"];
                _mapLayersVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
                _mapLayersVC.view.alpha = 0;
                
                [self.view addSubview:_mapLayersVC.view];
                [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) collectedDataButtonClicked:nil];
                [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) callSelectedDataDetailView:selectedData];
                
                [UIView animateWithDuration:0.1 animations:^{
                    CGRect formSheetRect = _mapLayersVC.view.frame;
                    formSheetRect.origin.x -= 488;
                    _mapLayersVC.view.alpha = 1;
                    
                } completion:^(BOOL finished) {
                    
                }];
                
            }];
            
        }];



        return;
    }
    
    if(_addTaskButtonView.alpha == 0){
        [self removeNewDataWindow];
    }
    
    [_searchButton setSelected:NO];
    [UIView animateWithDuration:0.1 animations:^{
        CGRect formSheetRect = _dataSearchNavNC.view.frame;
        formSheetRect.origin.x += 488;
        _dataSearchNavNC.view.alpha = 0;
        
    } completion:^(BOOL finished) {
        [_dataSearchNavNC.view removeFromSuperview];
        
        [_mapLayersButton setSelected:YES];
        
        _mapLayersVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mapLayersVC"];
        _mapLayersVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
        _mapLayersVC.view.alpha = 0;
        
        [self.view addSubview:_mapLayersVC.view];
        [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) collectedDataButtonClicked:nil];
        [((MapLayersAndCollectedDataView*)[((UINavigationController*)[[_mapLayersVC childViewControllers] objectAtIndex:0]) topViewController]) callSelectedDataDetailView:selectedData];
        
        [UIView animateWithDuration:0.1 animations:^{
            CGRect formSheetRect = _mapLayersVC.view.frame;
            formSheetRect.origin.x -= 488;
            _mapLayersVC.view.alpha = 1;
            
        } completion:^(BOOL finished) {
            
        }];
        
    }];

}

#pragma Handdrawing methods
- (void)beginHandDrawingMode :(NSInteger)index :(NSString*)mode
{
    [_handDrawingHandler setMode:index type:mode];
}

-(void)HandDrawingHandler:(HandDrawingHandler *)handler didFinishDrawing:(AGSGeometry *)geometry :(NSString *)type
{
    collectedData *newData;
    if(isReGathering && _toReGatheringData)
    {
        [[currentWorkSetManager sharedInstance] updateCollectedData :_toReGatheringData :geometry :_currentRecordingMainTYpe :_currentRecordingType];
        newData = _toReGatheringData;
    } else {
        newData = [[collectedData alloc] initWithAllAttr:@"" :@"" :@"1" :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"realname"] :[[NSDate date] toFormattedString] :[[NSDate date] toFormattedString] :nil :geometry :_currentRecordingMainTYpe :_currentRecordingType];
        
        [[[currentWorkSetManager sharedInstance] getCurrentWorkSet] addNewCollectedData:newData];
        [[currentWorkSetManager sharedInstance] addCollectedData:[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] name] :newData];
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAllCollectedDataOnMapview" object:nil];
    
    _collectedDataVC = (newCollectedDataViewViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"newCollectedDataViewController"];
    [_collectedDataVC setGeometry:geometry];
    [_collectedDataVC setData:newData];
    [_collectedDataVC setType:_currentRecordingType];
    [_collectedDataVC setMainType:_currentRecordingMainTYpe];
    _collectedDataVC.view.frame = CGRectMake(1024-488, 108-4, 488, 668);
    
    [self.view addSubview:_collectedDataVC.view];
    
    _mainMapVIew.touchDelegate = self;
    isReGathering = NO;
}


-(void)SpatialSearchHandler:(SpatialSearchHandler *)handler didFinishDrawing:(AGSGeometry *)geometry :(SpatialSearchMode)mode
{
    [self.mainMapVIew removeMapLayerWithName:@"HANDDRAWINGLAYER"];
    [self.mainMapVIew removeMapLayerWithName:@"Sketch layer"];
    
    if(mode == SpatialSearchModeLine){
        AGSPolyline *polyline = (AGSPolyline*)geometry;
        if([polyline numPoints] > 0){
            NSArray *foundArray = [SpatialSearchPolygonHelper searchTouchedGeometryUsing:geometry];
            
            
            [((SpatialSearchIndicatorViewController*)[((UINavigationController*)[[_dataSearchNavNC childViewControllers] objectAtIndex:0]) topViewController]) backToParentView];
            [((AttrDataSearchViewController*)[((UINavigationController*)[[_dataSearchNavNC childViewControllers] objectAtIndex:0]) topViewController]) showSpatialSearchedResult:foundArray];
            
            if([foundArray count] > 0){
                AGSGraphicsLayer* layer  = (AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"];
                [layer clearSelection];
                for(collectedData *d in foundArray){
                    AGSGraphic *foundG = [_graphicDict objectForKey:[d idNumber]];
                    
                    
                    [layer setSelected:YES forGraphic:foundG];
                }
            }
        }
    } else {
        AGSPolygon *polygon = (AGSPolygon*)geometry;
        if([polygon numPoints] > 0){
            NSArray *foundArray = [SpatialSearchPolygonHelper searchTouchedGeometryUsing:geometry];
            [((SpatialSearchIndicatorViewController*)[((UINavigationController*)[[_dataSearchNavNC childViewControllers] objectAtIndex:0]) topViewController]) backToParentView];
            [((AttrDataSearchViewController*)[((UINavigationController*)[[_dataSearchNavNC childViewControllers] objectAtIndex:0]) topViewController]) showSpatialSearchedResult:foundArray];
            
            if([foundArray count] > 0){
                AGSGraphicsLayer* layer  = (AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"];
                [layer clearSelection];
                for(collectedData *d in foundArray){
                    AGSGraphic *foundG = [_graphicDict objectForKey:[d idNumber]];
                    
                    
                    [layer setSelected:YES forGraphic:foundG];
                }
            }
        }
    }
    _mainMapVIew.touchDelegate = self;
}

#pragma AGSMapViewTouchDelegate Methods
-(void)mapView:(AGSMapView *)mapView didClickAtPoint:(CGPoint)screen mapPoint:(AGSPoint *)mappoint features:(NSDictionary *)features
{
    /*
    for(collectedData *d in [_currentWorkSet collectedDataList]){
        if([[AGSGeometryEngine defaultGeometryEngine] geometry:mappoint withinGeometry:[d geometry]]){
            [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] clearSelection];
            AGSGraphic *selectedG = [_graphicDict objectForKey:[d name]];
            [(AGSGraphicsLayer*)[self.mainMapVIew mapLayerForName:@"GATHERINGDRAWLAYER"] setSelected:YES forGraphic:selectedG];
            
        }
    }
     */
}

-(NSArray*)queryDataFromFeatureLayers:(NSString*)queryString
{
    _featureQueryResultList = [[NSMutableArray alloc] initWithCapacity:10];
    
    AGSQuery *query = [AGSQuery query];
    query.outFields = [NSArray arrayWithObjects:@"*",nil];
    query.returnGeometry = YES;
    query.text = queryString;
    for(AGSLayer *l in [_mainMapVIew mapLayers])
    {
        if([l isMemberOfClass:[AGSFeatureLayer class]])
        {
            if([l isVisible])
            {
                ((AGSFeatureLayer*)l).queryDelegate = self;
                [(AGSFeatureLayer*)l queryFeatures:query];
            }
        }
    }
    
    return nil;
}

- (void)featureLayer:(AGSFeatureLayer *)featureLayer operation:(NSOperation*)op didQueryFeaturesWithFeatureSet:(AGSFeatureSet *)featureSet
{
    if([featureLayer isVisible])
    {
        for(AGSGraphic *foundG in [featureSet features])
        {
            NSDictionary *d = [foundG allAttributes];
            NSLog(@"%@",d);
        }
    }
}

- (void)featureLayer:(AGSFeatureLayer *)featureLayer operation:(NSOperation*)op didFailQueryFeaturesWithError:(NSError *)error;
{
    
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
